//
//  TeilPickerAlertView.swift
//  PickerView
//
//  Created by 李成 on 2023/12/12.
//

import Foundation
import UIKit

/// 选择器展示类型的枚举
enum TeilPickerAlertType: Int {
    /// 日期时间
    case dateAndTime = 0
    /// 日期
    case date = 1
    /// 时间
    case time = 2
    /// 其他
    case other = 3
}

protocol TeilPickerAlertViewDelegate: NSObjectProtocol {
    func selectedItem(text: String, identifier: String)
}

class TeilPickerAlertView: UIView {
    /// 代理
    weak var delegate: TeilPickerAlertViewDelegate?
    
    /// 数据源的标识
    var alertIdentifier: String?
    
    /// 当前选择其的类型【默认为：日期时间】
    var type: TeilPickerAlertType = .dateAndTime
    
    /// 选择的结果
    var selectedStr: String = ""
    
    /// 标题
    var titleStr: String = "选择" {
        didSet {
            titleView.text = titleStr
        }
    }
    
    /// 背景的高度
    var bgHeight: CGFloat = 248.0
    
    /// 行高
    var rowHeight: CGFloat = 40.0
    
    /// 遮罩层的颜色
    var maskBackgroundColor: UIColor = .clear {
        didSet {
            backgroundColor = maskBackgroundColor
        }
    }
    
    /// 底部操作区域父视图的颜色
    var functionBackgroundColor: UIColor = .white {
        didSet {
            bgView.backgroundColor = functionBackgroundColor
        }
    }
    
    /// 选择器字体颜色
    var pickerTextColor: UIColor = .black
    
    /// 选择器字体
    var pickerFont: UIFont = UIFont(name: "PingFangSC-Regular", size: 16)!
    
    /// 取消按钮字体
    var cancelFont: UIFont = UIFont(name: "PingFangSC-Regular", size: 16.0)! {
        didSet {
            cancelView.titleLabel?.font = cancelFont
        }
    }
    
    /// 确认按钮字体
    var confirmFont: UIFont = UIFont(name: "PingFangSC-Regular", size: 16.0)! {
        didSet {
            confirmView.titleLabel?.font = confirmFont
        }
    }
    
    /// 取消按钮字体颜色
    var cancelTextColor: UIColor = .gray {
        didSet {
            cancelView.setTitleColor(cancelTextColor, for: .normal)
        }
    }
    
    /// 确认按钮字体颜色
    var confirmTextColor: UIColor = .blue {
        didSet {
            confirmView.setTitleColor(confirmTextColor, for: .normal)
        }
    }
    
    // MARK: 数据源
    /// 年
    var years = Array(1949...2099)
    /// 月
    private let months = Array(1...12)
    /// 天数数组会根据选择的【年份/月份】动态改变
    private var days = Array(1...31)
    /// 时
    private let hours = Array(0...23)
    /// 分
    private let minutes = Array(0...59)
    /// 秒
    private let seconds = Array(0...59)
    /// 非时间数据源
    var others: Array<String> = []
    
    /// 选择的年份
    private var selectedYear: Int?
    /// 选择的月份
    private var selectedMonth: Int?
    /// 选择的天数
    private var selectedDay: Int?
    /// 选择的时
    private var selectedHour: Int?
    /// 选择的分
    private var selectedMinute: Int?
    /// 选择的秒
    private var selectedSecond: Int?
    /// 选择的非时间数据
    private var selectedOther: Int?
    
    /// 存储31天的月份
    private let monthsWith31Days = Set([1, 3, 5, 7, 8, 10, 12])
    
    // MARK: 平年/闰年的判断函数
    /// 通过给定年份判断是否闰年
    private func isLeapYear(_ year: Int) -> Bool {
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
    }

    /// 根据年份和月份返回天数
    private func daysInMonth(month: Int, year: Int) -> Int {
        if monthsWith31Days.contains(month) {
            return 31
        } else if month == 2 {
            return isLeapYear(year) ? 29 : 28
        } else {
            return 30
        }
    }
    
    // MARK: 存储当前选择的年份和月份
    /// 默认值，当前选择的年份
    private var currentYear: Int = 2023
    /// 默认值，当前选择的月份
    private var currentMonth: Int = 1
    
    // MARK: UI控件
    /// 底部背景
    lazy var bgView = {
        let view = UIView(frame: bounds)
        view.backgroundColor = colorFromHexString("#FFFFFF", alpha: 1.0)
        view.layer.cornerRadius = 12.0
        view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        view.layer.masksToBounds = true
        return view
    }()
    
    /// 取消
    private lazy var cancelView = {
        let btn = UIButton(frame: .zero)
        btn.setTitle("取消", for: UIControl.State.normal)
        btn.setTitleColor(colorFromHexString("#595959", alpha: 1.0), for: UIControl.State.normal)
        btn.titleLabel?.font = cancelFont
        btn.addTarget(self, action: #selector(cancelTouch), for: .touchUpInside)
        return btn
    }()
    
    /// 确定
    private lazy var confirmView = {
        let btn = UIButton(frame: .zero)
        btn.setTitle("确定", for: UIControl.State.normal)
        btn.setTitleColor(colorFromHexString("#4385FF", alpha: 1.0), for: UIControl.State.normal)
        btn.titleLabel?.font = confirmFont
        btn.addTarget(self, action: #selector(confirmTouch), for: .touchUpInside)
        return btn
    }()
    
    /// 标题
    private lazy var titleView = {
        let label = UILabel(frame: .zero)
        label.textAlignment = .center
        label.font = UIFont(name: "PingFangSC-Semibold", size: 16)
        label.textColor = colorFromHexString("#262626")
        label.text = "选择"
        return label
    }()
    
    /// 分隔线
    private lazy var lineView = {
        let line = UIView()
        line.backgroundColor = .black
        return line
    }()
    
    
    /// 时间选择器
    private lazy var pickerView = {
        let picker = UIPickerView()
        picker.delegate = self
        picker.dataSource = self
        picker.tintColor = .clear
        return picker
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(bgView)
        bgView.addSubview(cancelView)
        bgView.addSubview(confirmView)
        bgView.addSubview(titleView)
        bgView.addSubview(lineView)
        bgView.addSubview(pickerView)
        
        bgView.frame = CGRect(x: 0, y: bounds.height - bgHeight - kBottomSafeAreaInsets, width: bounds.width, height: kBottomSafeAreaInsets+bgHeight)
        cancelView.frame = CGRect(x: 0, y: 14, width: 64, height: 24)
        confirmView.frame = CGRect(x: bounds.width - 64, y: 14, width: 64, height: 24)
        titleView.frame = CGRect(x: CGRectGetWidth(cancelView.frame), y: CGRectGetMinY(cancelView.frame), width: bounds.width - CGRectGetWidth(cancelView.frame) - confirmView.frame.width, height: 24)
        lineView.frame = CGRect(x: 0, y: CGRectGetMaxY(cancelView.frame)+11.5, width: CGRectGetWidth(frame), height: 0.5)
        
        pickerView.frame = CGRect(x: 0, y: CGRectGetMaxY(lineView.frame), width: CGRectGetWidth(frame), height: bgHeight - CGRectGetMaxY(lineView.frame))
        
        
    }
    
    /// 显示方法
    func showAlert(view: UIView) {
        view.addSubview(self)
        if type == .dateAndTime {
            /// 初始化选择器的行数，以匹配当前时间
            let currentDate = Date()
            let calendar = Calendar.current

            selectedYear = calendar.component(.year, from: currentDate)
            selectedMonth = calendar.component(.month, from: currentDate)
            selectedDay = calendar.component(.day, from: currentDate)
            selectedHour = calendar.component(.hour, from: currentDate)
            selectedMinute = calendar.component(.minute, from: currentDate)
            selectedSecond = calendar.component(.second, from: currentDate)

            pickerView.selectRow(years.firstIndex(of: selectedYear ?? 2022) ?? 0, inComponent: 0, animated: false)
            pickerView.selectRow(months.firstIndex(of: selectedMonth ?? 1) ?? 0, inComponent: 1, animated: false)
            pickerView.selectRow(days.firstIndex(of: selectedDay ?? 1) ?? 0, inComponent: 2, animated: false)
            pickerView.selectRow(hours.firstIndex(of: selectedHour ?? 0) ?? 0, inComponent: 3, animated: false)
            pickerView.selectRow(minutes.firstIndex(of: selectedMinute ?? 0) ?? 0, inComponent: 4, animated: false)
            pickerView.selectRow(seconds.firstIndex(of: selectedSecond ?? 0) ?? 0, inComponent: 5, animated: false)
            
        }
        else if type == .date {
            /// 初始化选择器的行数，以匹配当前时间
            let currentDate = Date()
            let calendar = Calendar.current

            selectedYear = calendar.component(.year, from: currentDate)
            selectedMonth = calendar.component(.month, from: currentDate)
            selectedDay = calendar.component(.day, from: currentDate)

            pickerView.selectRow(years.firstIndex(of: selectedYear ?? 2022) ?? 0, inComponent: 0, animated: false)
            pickerView.selectRow(months.firstIndex(of: selectedMonth ?? 1) ?? 0, inComponent: 1, animated: false)
            pickerView.selectRow(days.firstIndex(of: selectedDay ?? 1) ?? 0, inComponent: 2, animated: false)
        }
        else if type == .time {
            /// 初始化选择器的行数，以匹配当前时间
            let currentDate = Date()
            let calendar = Calendar.current
            selectedHour = calendar.component(.hour, from: currentDate)
            selectedMinute = calendar.component(.minute, from: currentDate)
            selectedSecond = calendar.component(.second, from: currentDate)
            
            pickerView.selectRow(hours.firstIndex(of: selectedHour ?? 0) ?? 0, inComponent: 0, animated: false)
            pickerView.selectRow(minutes.firstIndex(of: selectedMinute ?? 0) ?? 0, inComponent: 1, animated: false)
            pickerView.selectRow(seconds.firstIndex(of: selectedSecond ?? 0) ?? 0, inComponent: 2, animated: false)
        }
        else {
            pickerView.selectRow(selectedOther ?? 0, inComponent: 0, animated: false)
        }
        
        updateSelectedResult()
        
    }
    
    // MARK: action
    /// 取消按钮点击事件
    @objc func cancelTouch() {
        
        removeFromSuperview()
        
    }
    
    /// 确认按钮点击事件
    @objc func confirmTouch() {
        
        delegate?.selectedItem(text: selectedStr, identifier: alertIdentifier ?? "")
        cancelTouch()
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}


extension TeilPickerAlertView: UIPickerViewDelegate, UIPickerViewDataSource {
    // MARK: UIPickerViewDataSource
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        if type == .dateAndTime {
            /// 年、月、日、时、分、秒
            return 6
        }
        else if type == .date || type == .time {
            return 3
        }
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if type == .dateAndTime || type == .date {
            switch component {
            case 0:
                return years.count
            case 1:
                return months.count
            case 2:
                return days.count
            case 3:
                return hours.count
            case 4:
                return minutes.count
            case 5:
                return seconds.count
            default:
                return 0
            }
        }
        else if type == .time {
            switch component {
            case 0:
                return hours.count
            case 1:
                return minutes.count
            case 2:
                return seconds.count
            default:
                return 0
            }
        }
        else {
            return others.count
        }
    }

    // MARK: - UIPickerViewDelegate
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if type == .dateAndTime || type == .date {
            switch component {
            case 0:
                return "\(years[row])年"
            case 1:
                return "\(months[row])月"
            case 2:
                return "\(days[row])日"
            case 3:
                return "\(hours[row])时"
            case 4:
                return "\(minutes[row])分"
            case 5:
                return "\(seconds[row])秒"
            default:
                return nil
            }
        }
        else if type == .time {
            switch component {
            case 0:
                return "\(hours[row])时"
            case 1:
                return "\(minutes[row])分"
            case 2:
                return "\(seconds[row])秒"
            default:
                return nil
            }
        }
        else {
            return "\(others[row])"
        }
        
    }
    
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return rowHeight
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let label = UILabel()
        /// 对齐方式
        label.textAlignment = .center
        /// 设置字体大小
        label.font = pickerFont
        /// 文本内容
        label.text = pickerView.delegate?.pickerView?(pickerView, titleForRow: row, forComponent: component)
        /// 文本颜色
        label.textColor = pickerTextColor
        return label
    }
    

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if type == .date || type == .dateAndTime {
            switch component {
            case 0: /// 年被选择时
                currentYear = years[row]
            case 1: /// 月被选择时
                currentMonth = months[row]
            case 2: /// Day 不需要更新 year 或 month
                break
            default:
                break
            }
            
            /// 更新天数数组
            days = Array(1...daysInMonth(month: currentMonth, year: currentYear))
            
            /// 重新加载日component
            pickerView.reloadComponent(2)
            
            /// 确保日组件的选中行在更新的天数范围内
            let daySelectedRow = pickerView.selectedRow(inComponent: 2)
            if daySelectedRow >= days.count {
                pickerView.selectRow(days.count - 1, inComponent: 2, animated: true)
            }
        }
        
        updateSelectedResult()
    }

    /// 更新选定的
    func updateSelectedResult() {
        if type == .dateAndTime {
            selectedYear = years[pickerView.selectedRow(inComponent: 0)]
            selectedMonth = months[pickerView.selectedRow(inComponent: 1)]
            selectedDay = days[pickerView.selectedRow(inComponent: 2)]
            selectedHour = hours[pickerView.selectedRow(inComponent: 3)]
            selectedMinute = minutes[pickerView.selectedRow(inComponent: 4)]
            selectedSecond = seconds[pickerView.selectedRow(inComponent: 5)]

            let selectedDateTime = String(format: "%04d-%02d-%02d %02d:%02d:%02d",
                                          selectedYear ?? 0, selectedMonth ?? 0, selectedDay ?? 0,
                                          selectedHour ?? 0, selectedMinute ?? 0, selectedSecond ?? 0)

            print("Selected Date and Time: \(selectedDateTime)")
            selectedStr = selectedDateTime
            
        }
        if type == .date {
            selectedYear = years[pickerView.selectedRow(inComponent: 0)]
            selectedMonth = months[pickerView.selectedRow(inComponent: 1)]
            selectedDay = days[pickerView.selectedRow(inComponent: 2)]

            let selectedDateTime = String(format: "%04d-%02d-%02d",
                                          selectedYear ?? 0, selectedMonth ?? 0, selectedDay ?? 0)

            print("Selected Date and Time: \(selectedDateTime)")
            selectedStr = selectedDateTime
        }
        if type == .time {
            selectedHour = hours[pickerView.selectedRow(inComponent: 0)]
            selectedMinute = minutes[pickerView.selectedRow(inComponent: 1)]
            selectedSecond = seconds[pickerView.selectedRow(inComponent: 2)]

            let selectedDateTime = String(format: "%02d:%02d:%02d",
                                          selectedHour ?? 0, selectedMinute ?? 0, selectedSecond ?? 0)

            print("Selected Date and Time: \(selectedDateTime)")
            selectedStr = selectedDateTime
        }
        else if type == .other {
            let str = others[pickerView.selectedRow(inComponent: 0)]
            print("str：\(str)")
            selectedStr = str
        }
    }
    
    
}



/// 16进制颜色设置可以控制 alpha
func colorFromHexString(_ hexString: String, alpha: CGFloat = 1.0) -> UIColor? {
    var formattedString = hexString.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if formattedString.hasPrefix("#") {
        formattedString.remove(at: formattedString.startIndex)
    }

    if formattedString.count != 6 {
        return nil
    }

    var rgbValue: UInt64 = 0
    Scanner(string: formattedString).scanHexInt64(&rgbValue)

    let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
    let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
    let blue = CGFloat(rgbValue & 0x0000FF) / 255.0

    return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}

/// 刘海屏的底部安全距离
var kBottomSafeAreaInsets: CGFloat {
    if #available(iOS 13.0, *) {
        let scene = UIApplication.shared.connectedScenes.first
        guard let windowScene = scene as? UIWindowScene else { return 0 }
        guard let window = windowScene.windows.first else { return 0 }
//            MPPrint("安全距离的高度：\(window.safeAreaInsets.bottom)")
        return window.safeAreaInsets.bottom
    }
    return 0.0
}

